/// <summary>
// DBLinq.MySqlProviders - .NET Providers for MySql using the framework DBLinq under MIT license, author Jiri George Moudry
// http://linq.to/db
// and the CodeFx.MySqlProviders under GNU licence, author Laurent Morisseau
// http://www.codeplex.com/CodeFxMySqlProvider
//
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation; either version 2 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
//
// Laurent Morisseau
/// </summary>
/// <author><a href="mailto:laurent.morisseau@gmail.com">Laurent Morisseau</a></author>

using System;
using System.Collections.Generic;
using System.Text;
using System.Collections.Specialized;
using System.Configuration.Provider;
using System.Security.Cryptography;
using System.Collections;
using System.Web.Security;
using System.Globalization;

namespace DBLinq.MySqlProviders
{
    public static class SecUtility
    {
        internal static int GetIntValue(NameValueCollection config, string valueName, int defaultValue, bool zeroAllowed, int maxValueAllowed)
        {
            int num1;
            string text1 = config[valueName];
            if (text1 == null)
            {
                return defaultValue;
            }
            if (!int.TryParse(text1, out num1))
            {
                if (zeroAllowed)
                {
                    throw new ProviderException("Value_must_be_non_negative_integer");
                }
                throw new ProviderException("Value_must_be_positive_integer");
            }
            if (zeroAllowed && (num1 < 0))
            {
                throw new ProviderException("Value_must_be_non_negative_integer");
            }
            if (!zeroAllowed && (num1 <= 0))
            {
                throw new ProviderException("Value_must_be_positive_integer");
            }
            if ((maxValueAllowed > 0) && (num1 > maxValueAllowed))
            {
                throw new ProviderException("Value_too_big");
            }
            return num1;
        }

        internal static string UnEncodePassword(string pass, int passwordFormat)
        {
            switch (passwordFormat)
            {
                case 0:
                    return pass;

                case 1:
                    throw new ProviderException("Provider_can_not_decode_hashed_password");
            }
            byte[] buffer1 = Convert.FromBase64String(pass);
            //byte[] buffer2 = DecryptPassword(buffer1);
            byte[] buffer2 = buffer1;
            if (buffer2 == null)
            {
                return null;
            }
            return Encoding.Unicode.GetString(buffer2, 0x10, buffer2.Length - 0x10);
        }


        internal static string EncodePassword(string password, MembershipPasswordFormat PasswordFormat)
        {
            string encodedPassword = password;

            switch (PasswordFormat)
            {
                case MembershipPasswordFormat.Clear:
                    break;
                case MembershipPasswordFormat.Encrypted:
                    //encodedPassword = Convert.ToBase64String(EncryptPassword(Encoding.Unicode.GetBytes(password)));
                    encodedPassword = Convert.ToBase64String(Encoding.Unicode.GetBytes(password));
                    break;
                case MembershipPasswordFormat.Hashed:
                    //HMACSHA1 hash = new HMACSHA1();
                    //hash.Key = HexToByte(encryptionKey);
                    //encodedPassword =
                    //  Convert.ToBase64String(hash.ComputeHash(Encoding.Unicode.GetBytes(password)));
                    throw new ProviderException("Unsupported password format.");
                default:
                    throw new ProviderException("Unsupported password format.");
            }

            return encodedPassword;
        }


        internal static string UnEncodePassword(string encodedPassword, MembershipPasswordFormat PasswordFormat)
        {
            string password = encodedPassword;

            switch (PasswordFormat)
            {
                case MembershipPasswordFormat.Clear:
                    break;
                case MembershipPasswordFormat.Encrypted:
                    //password = Encoding.Unicode.GetString(DecryptPassword(Convert.FromBase64String(password)));
                    password = Encoding.Unicode.GetString(Convert.FromBase64String(password));
                    break;
                case MembershipPasswordFormat.Hashed:
                    throw new ProviderException("Cannot unencode a hashed password.");
                default:
                    throw new ProviderException("Unsupported password format.");
            }

            return password;
        }

        internal static string GetExceptionText(int status)
        {
            string text1;
            switch (status)
            {
                case 0:
                    return string.Empty;

                case 1:
                    text1 = "Membership_UserNotFound";
                    break;

                case 2:
                    text1 = "Membership_WrongPassword";
                    break;

                case 3:
                    text1 = "Membership_WrongAnswer";
                    break;

                case 4:
                    text1 = "Membership_InvalidPassword";
                    break;

                case 5:
                    text1 = "Membership_InvalidQuestion";
                    break;

                case 6:
                    text1 = "Membership_InvalidAnswer";
                    break;

                case 7:
                    text1 = "Membership_InvalidEmail";
                    break;

                case 0x63:
                    text1 = "Membership_AccountLockOut";
                    break;

                default:
                    text1 = "Provider_Error";
                    break;
            }
            return text1;
        }
        internal static string EncodePassword(string pass, int passwordFormat, string salt)
        {
            if (passwordFormat == 0)
            {
                return pass;
            }
            byte[] buffer1 = Encoding.Unicode.GetBytes(pass);
            byte[] buffer2 = Convert.FromBase64String(salt);
            byte[] buffer3 = new byte[buffer2.Length + buffer1.Length];
            byte[] buffer4 = null;
            Buffer.BlockCopy(buffer2, 0, buffer3, 0, buffer2.Length);
            Buffer.BlockCopy(buffer1, 0, buffer3, buffer2.Length, buffer1.Length);
            if (passwordFormat == 1)
            {
                throw new NotSupportedException("Membership_EncodePasswordFormat_1_not_supported");
                //HashAlgorithm algorithm1 = HashAlgorithm.Create(Membership.HashAlgorithmType);
                //if ((algorithm1 == null) && Membership.IsHashAlgorithmFromMembershipConfig)
                //{
                //    RuntimeConfig.GetAppConfig().Membership.ThrowHashAlgorithmException();
                //}
                //buffer4 = algorithm1.ComputeHash(buffer3);
            }
            else
            {
                //buffer4 = EncryptPassword(buffer3);
                buffer4 = buffer3;
            }
            return Convert.ToBase64String(buffer4);
        }
        internal static bool ValidateParameter(ref string param, bool checkForNull, bool checkIfEmpty, bool checkForCommas, int maxSize)
        {
            if (param == null)
            {
                return !checkForNull;
            }
            param = param.Trim();
            if (((!checkIfEmpty || (param.Length >= 1)) && ((maxSize <= 0) || (param.Length <= maxSize))) && (!checkForCommas || !param.Contains(",")))
            {
                return true;
            }
            return false;
        }

        internal static string GenerateSalt()
        {
            byte[] buffer1 = new byte[0x10];
            new RNGCryptoServiceProvider().GetBytes(buffer1);
            return Convert.ToBase64String(buffer1);
        }

        internal static void CheckParameter(ref string param, bool checkForNull, bool checkIfEmpty, bool checkForCommas, int maxSize, string paramName)
        {
            if (param == null)
            {
                if (checkForNull)
                {
                    throw new ArgumentNullException(paramName);
                }
            }
            else
            {
                param = param.Trim();
                if (checkIfEmpty && (param.Length < 1))
                {
                    throw new ArgumentException("Parameter_can_not_be_empty");
                }
                if ((maxSize > 0) && (param.Length > maxSize))
                {
                    throw new ArgumentException("Parameter_too_long");
                }
                if (checkForCommas && param.Contains(","))
                {
                    throw new ArgumentException("Parameter_can_not_contain_comma");
                }
            }
        }

        internal static void CheckArrayParameter(ref string[] param, bool checkForNull, bool checkIfEmpty, bool checkForCommas, int maxSize, string paramName)
        {
            if (param == null)
            {
                throw new ArgumentNullException(paramName);
            }
            if (param.Length < 1)
            {
                throw new ArgumentException("Parameter_array_empty");
            }
            Hashtable hashtable1 = new Hashtable(param.Length);
            for (int num1 = param.Length - 1; num1 >= 0; num1--)
            {
                SecUtility.CheckParameter(ref param[num1], checkForNull, checkIfEmpty, checkForCommas, maxSize, paramName + "[ " + num1.ToString(CultureInfo.InvariantCulture) + " ]");
                if (hashtable1.Contains(param[num1]))
                {
                    throw new ArgumentException("Parameter_duplicate_array_element");
                }
                hashtable1.Add(param[num1], param[num1]);
            }
        }
    }
}
